package org.example.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 张琪
 * @date 2024/4/17 16:18
 */
public class SynchronizedExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        SynchronizedExample synchronizedExample = new SynchronizedExample();
        SynchronizedExample synchronizedExample2 = new SynchronizedExample();

        // synchronized 修饰代码块, 对当前对象进行同步; 不同对象间不同步
//        executorService.execute(synchronizedExample::syncObjectTest);
//        executorService.execute(synchronizedExample2::syncObjectTest);

        // synchronized 修饰方法, 对整个方法进行同步; 与修饰代码块相同, 不同对象间不同步
//        executorService.execute(synchronizedExample::syncMethodTest);
//        executorService.execute(synchronizedExample2::syncMethodTest);

        // synchronized 修饰类, 对整个类进行同步; 不同对象间可以进行同步
//        executorService.execute(synchronizedExample::syncClassTest);
//        executorService.execute(synchronizedExample2::syncClassTest);

        // synchronized 修饰静态方法, 对整个类进行同步
        executorService.execute(SynchronizedExample::syncStaticMethodTest);
//            executorService.shutdown();
    }

    public void syncObjectTest() {
        // synchronized (this) 只能对一个对象进行代码块同步
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "  " + i);
            }
        }
    }

    public synchronized void syncMethodTest() {
        // synchronized 修饰方法, 对整个方法进行同步; 不同对象执行同一个方法时, 都会进行同步
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "  " + i);
        }
    }

    public void syncClassTest() {
        // synchronized 修饰静态方法, 对整个类进行同步
        synchronized (SynchronizedExample.class) {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "  " + i);
            }
        }
    }

    public synchronized static void syncStaticMethodTest() {
        // synchronized 修饰静态方法, 对整个类进行同步
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "  " + i);
        }
    }

}
